package com.wsz.logistic.controller.admin;

import com.wsz.logistic.bean.Userinfo;
import com.wsz.logistic.common.form.LoginForm;
import com.wsz.logistic.common.util.R;
import com.wsz.logistic.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private UserinfoService userinfoService;

    @GetMapping("/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 系统后台登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(LoginForm loginForm, HttpSession session) {
        Userinfo userinfo = userinfoService.login(loginForm);
        if (userinfo != null) {
            if (userinfo.getRole() == 1 && userinfo.getStatus() == 1) {
                session.setAttribute("loginInfo", userinfo);
                return R.ok();
            } else {
                return R.error("账号异常！");
            }
        } else {
            return R.error("用户名或密码不正确！");
        }
    }

    @GetMapping("/ahome")
    public String ahome() {
        return "admin/ahome";
    }

    @GetMapping("/welcome")
    public String welcome() {
        return "admin/welcome";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginInfo");
        return "redirect:/admin/login";
    }
}
